package dao;

import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
@Qualifier("userDao")
public class UserDaoImpl implements UserDao {
    // 自动注入 JdbcTemplate
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * This is the method to be used to create
     * a record in the User table.
     *
     * @param username
     * @param email
     * @param password_hash
     * @param about_me
     * @param last_seen
     */
    @Override
    public void create(String username, String email, String password_hash, String about_me, LocalDateTime last_seen) {
        // 插入语句
        String sql = "insert into user(username,email,password_hash,about_me,last_seen) value (?,?,?,?,?)";
        jdbcTemplate.update(sql,username,email,password_hash,about_me,last_seen);
    }

    /**
     * This is the method to be used to list down
     * a record from the User table corresponding
     * to a passed student id.
     *
     * @param id
     */
    @Override
    public User getUser(Integer id) {
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
    }

    /**
     * This is the method to be used to list down
     * all the records from the User table.
     */
    @Override
    public List<User> listUsers() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<>(User.class));
    }

    /**
     * This is the method to be used to delete
     * a record from the User table corresponding
     * to a passed student id.
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql,id);
    }

    /**
     * This is the method to be used to update
     * a record into the User table.
     *
     * @param id
     * @param about_me
     */
    @Override
    public void update(Integer id, String about_me) {
        String sql = "update user set about_me = ? where id = ?";
        jdbcTemplate.update(sql,about_me,id);
    }
}
